package com.lzy.cloud.payment.pay.weixin;

import com.lzy.cloud.payment.constants.CommonConstants;
import com.lzy.framework.core.ensure.Ensure;
import net.sf.json.JSONObject;
import org.jdom2.JDOMException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


public class WxService{
	
	private static final Logger logger = LoggerFactory.getLogger(WxService.class);
	
	/**
	 * 获取通知数据。
	 * @param request HTTP上下文对象
	 * @return 通知数据
	 * @throws IOException
	 * @throws JDOMException
	 */
	public JSONObject processNotify(HttpServletRequest request){
		try {
				InputStream inStream = request.getInputStream();
				ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = inStream.read(buffer)) != -1) {
					outSteam.write(buffer, 0, len);  
				}
				outSteam.close();  
				inStream.close(); 
				String result = new String(outSteam.toByteArray(), "utf-8");
				logger.info("----------接收到微信的异步参数-----------"+JSONObject.fromObject(WxPayUtil.toMap(result)));
				return JSONObject.fromObject(WxPayUtil.toMap(result));
		} catch (Exception e) {
			logger.info("----获取失败----");
		}
		return null;
	}
	/**
	 * 返回微信请求
	 * @param flag
	 * @return
	 */
	public static String responseWx(boolean flag){
		WxPayData data = new WxPayData();
		if(flag){
			data.put(CommonConstants.RETURN_CODE, CommonConstants.SUCCESS);
			data.put(CommonConstants.RETURN_MSG, CommonConstants.OK);
		}else{
			data.put(CommonConstants.RETURN_CODE, CommonConstants.FAIL);
			data.put(CommonConstants.RETURN_MSG, CommonConstants.FAIL); 
		}
		return data.toXml();
	}
	/**
	 * 微信返回成功支付时间
	 * @param dateString
	 * @return
	 */
	public static Date StrToDate(String dateString) {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
        try {
	        Date date = df.parse(dateString);
	        return date;
        }catch(Exception e){
        	e.printStackTrace();
        }
        return null;
	}
	/**
	 * 获取公众号支付openid
	 * @param code
	 * @return
	 */
	public static JSONObject getWebOpenid(String code){
		String url = Config.WECHAT_OPENID_URL +"?appid="+Config.WEB_APPID+"&secret="+Config.WEB_APPSECRET+"&code="+code+"&grant_type=authorization_code";
		return getBaseOpenid(url);
	}

//	/**
//	 * 获取小程序openid
//	 * @param code
//	 * @param appletKDCDto
//	 * @return
//	 */
//	public static JSONObject getAppOpenid(String code,AppletKDCDto appletKDCDto){
//		String url = Config.WECHAT_JS_OPENID_URL +"?appid="+appletKDCDto.getAppId()+"&secret="+appletKDCDto.getAppSecret()+"&js_code="+code+"&grant_type=authorization_code";
//		return getBaseOpenid(url);
//	}

	/**
	 * 获取登录用户信息
	 * @param accessToken
	 * @param openId
	 * @return
	 */
	public static JSONObject getUserInfo(String accessToken,String openId){
		String url = Config.WECHAT_USERINFO +"?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";
		return getBaseOpenid(url);
	}
	/**
	 * 获取openid 基础方法
	 * @param url
	 * @return
	 */
	public static JSONObject getBaseOpenid(String url){
		logger.info("------请求获取openid的url------"+url);
		String result = WxPayUtil.sendHttp(url, "POST", null);
		logger.info("--------请求结果---------"+result);
		JSONObject json = JSONObject.fromObject(result);
		if(json != null && json.containsKey("openid")) return  json;
		return null;
	}

	/**
	 * 微信统一返回(公众账号支付和微信小程序)
	 * @param result
	 * @param dt
	 * @return
	 */
	public static Map<String,Object> getWebWxResponse(WxPayData result,Date dt){
		WxPayData resultParams = new WxPayData();
		if (result.get(CommonConstants.RETURN_CODE).equals(CommonConstants.SUCCESS) && result.get(CommonConstants.RESULT_CODE).equals(CommonConstants.SUCCESS)) {
			resultParams = WxPayApi.getWebResponseData(result,dt);
			logger.info("返回提交数据---：" + resultParams.toJson());
			return resultParams.toMap();
		} else {
			Ensure.that(true).isFalse("09000009");  //微信统一下单异常
			logger.info("统一下单异常");
		}
		return null;
	}
	/**
	 * 微信统一返回（App支付）
	 * @param result
	 * @param dt
	 * @return
	 */
	public static Map<String,Object> getAppWxResponse(WxPayData result,Date dt){
		WxPayData resultParams = new WxPayData();
		if (result.get(CommonConstants.RETURN_CODE).equals(CommonConstants.SUCCESS) && result.get(CommonConstants.RESULT_CODE).equals(CommonConstants.SUCCESS)){
			resultParams = WxPayApi.getAppResponseData(result,dt);
			logger.info("APP提交数据："+resultParams.toJson());
			return resultParams.toMap();
		}else{
			Ensure.that(true).isFalse("09000009");  //微信统一下单异常
			logger.info("统一下单异常");
		}
		return null;
	}
	public static void main(String[] args) {
		/*WebPayDTO wb = new WebPayDTO();
		wb.setCode("001wySPE0Cs15f2dzZPE0BdyPE0wySPl");*/
		//getOpenid("061iTcM613ARtS1Oc5O61dsSL61iTcMQ",0);
	}
}
